package diva.canvaslibrary.client.particles;

import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.ImageElement;

import static diva.lib.lang.Lang.iterate;
import static diva.lib.lang.Lang.list;

import diva.gwtlib.client.Point;
import diva.lib.collections.Iteration;
import diva.lib.collections.List;

public class ParticleEmiter implements Object2D {

  private static final int PARTICLE_COUNT_LIMIT = 10;
  private final ImageElement image = Document.get().createImageElement();
  private final List<Particle> particles = list();
  private final List<Particle> spareParticles = list();
  private Point position;
  private double drag = 0.9;
  private Size screenSize;
  private double gravity = -0.15;

  public ParticleEmiter(String imageSrc, Point position) {
    this.position = position;
    image.setSrc(imageSrc);
  }

  public void draw(Context2d canvas2d) {
    if (particles.size() < PARTICLE_COUNT_LIMIT) if (spareParticles.size() == 0)
      particles.add(new Particle(image, position, screenSize));
    else {
      Particle particle = spareParticles.remove(0);
      particle.reset(position);
      particles.add(particle);
    }

    Iteration<Particle> particlesIteration = iterate(particles);
    for (Particle particle : particlesIteration) {
      particle.update(drag, gravity);
      if (!particle.isEnabled()) {
        particlesIteration.remove();
        spareParticles.add(particle);
      }
      if (particle.isEnabled()) particle.draw(canvas2d);
    }
  }

  public void setDrag(double drag) {
    this.drag = drag;
  }

  public void setGravity(double gravity) {
    this.gravity = gravity;
  }

  public void setPosition(int x, int y) {
    position = new Point(x, y);
  }

  public void setScreenSize(Size screenSize) {
    this.screenSize = screenSize;
  }
}
